<template>
  <div>
    <el-form  ref="dataCreateOrderForm" class="demo-ruleForm" :model="orderVO" label-position="right"
             label-width="80px"
             style='width: 100%;'>
      <el-row>
        <el-col :span="12">
          <el-form-item label="客户" prop="customerId" :rules="[
            { required: true, message: '请选择客户', trigger: 'change' }
          ]" >
          <el-select class="filter-item" v-model="orderVO.customerId" filterable placeholder="请选择">
            <el-option v-for="item in customerOptions" :key="item.id"
                       :label="item.realName!=''?item.realName+'('+item.nikeName+')':item.nikeName" :value="item.id">
              <span style="float: left">{{ item.realName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.nikeName }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item  label="取货方式">
          <el-select v-model="orderVO.receiptType" placeholder="请选择">
            <el-option v-for="item in receiptTypeOption" :key="item.value" :label="item.name" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="产品列表" >
        <el-button @click="handleAddProduct">添加</el-button>
        <el-table stripe
                  show-summary
                  :data="orderVO.orderProducts"
                  style="width: 100%" v-loading="productlistLoading" element-loading-text="玩命加载中">
          <el-table-column
            type="index"
            width="50">
          </el-table-column>
          <el-table-column
            label="名称"
            min-width="200">
            <template slot-scope="scope">
              <div>{{ scope.row.productName}}<span
                v-if="scope.row.productModel!=''">({{ scope.row.productModel}})</span></div>
            </template>
          </el-table-column>
          <el-table-column
            sortable
            label="单价"
            min-width="23%">
            <template slot-scope="scope"  prop="productPrice">
            <el-input :rules="[{ required: true, message: '年龄不能为空'},{ type: 'number', message: '年龄必须为数字值'}]" v-model.number="scope.row.productPrice" placeholder="单价"></el-input>
          </template>
          </el-table-column>
          <el-table-column
            sortable
            prop="productNum"
            label="数量"
            min-width="23%">
            <template slot-scope="scope">
              <el-input  controls-position="right" :min="0"  size="large" style="width: 100%" v-model.number="scope.row.productNum" placeholder="数量"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            sortable
            prop="productTotalPrice"
            label="小计"
            min-width="20%">
          </el-table-column>
          <el-table-column
            label="操作"
            min-width="10%">
            <template slot-scope="scope">
              <el-button
                @click.native.prevent="deleteRow(scope.$index, orderVO.orderProducts)"
                type="text"
                size="small">
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入备注，非必填"
                  v-model="orderVO.remark">
        </el-input>
      </el-form-item>
      <el-row>
        <el-col :span="8">
          <div class="grid-content bg-purple">
          <el-form-item label="联系方式" prop="contacts" >
            <el-input type="text" v-model="orderVO.contacts" placeholder="收件人"></el-input>
          </el-form-item>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
          <el-input type="text" v-model="orderVO.mobilePhone" placeholder="联系电话"></el-input>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content bg-purple">
          <el-input type="text" v-model="orderVO.address" placeholder="具体地址"></el-input>
          </div>
        </el-col>
      </el-row>
      <el-form-item>
        <el-button v-if="this.orderVO.id !== ''" type="primary" @click="updateOrderHandle('dataCreateOrderForm')">更新</el-button>
        <el-button v-if="this.orderVO.id == ''" type="primary" @click="saveOrderHandle('dataCreateOrderForm')">下单</el-button>
        <el-button @click="resetForm('dataCreateOrderForm')">重置</el-button>
      </el-form-item>
    </el-form>
    <el-dialog :title="textMap[dialogStatus]" :visible="dialogProductVisible" append-to-body  center>
      <el-form ref="dataProductForm" :model="product" label-position="right" label-width="90px" style='width: 60%;'>
        <el-form-item label="名称">
          <el-cascader
            placeholder="试试搜索：雪花秀"
            :options="productOptions"
            v-model="val"
            @change="handleItemChange"
            filterable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="规格型号">
          <el-input v-model="product.productModel" placeholder="规格型号"></el-input>
        </el-form-item>
        <el-form-item label="单价">
          <el-input-number v-model.number="product.productPrice" auto-complete="off" :min="1" placeholder="单价"></el-input-number>
        </el-form-item>
        <el-form-item label="数量">
          <el-input-number  v-model.number="product.productNum" :min="1" label="数量"></el-input-number>
        </el-form-item>
        <el-form-item label="小计">
          <el-button type="text" >{{product.productPrice*product.productNum}}</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogProductVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="addDomain('dataProductForm')">确定</el-button>
        <!--<el-button v-else type="primary" @click="updateData">{{$t('table.confirm')}}</el-button>-->
      </div>
    </el-dialog>

  </div>
</template>
<style>
  .time {
    font-size: 13px;
    color: #999;
  }

  .bottom {
    margin-top: 13px;
    line-height: 12px;
  }

  .button {
    padding: 0;
    float: right;
  }

  .image {
    width: 100%;
    display: block;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }

  .clearfix:after {
    clear: both
  }
</style>


<script>
  import { saveOrderList, updateOrderList, findOrderById, findAllProductList, findAllCustomerList } from '@/api/order'
  // import waves from '@/directive/waves' // 水波纹指令
  // import { parseTime } from '@/utils'
  export default {
    name: 'order-create',
    props: ['orderId', 'createVisable'],
    data() {
      return {
        val: [],
        productlistLoading: false,
        productOptions: [],
        productData: [],
        customerOptions: [],
        tableKey: 0,
        list: null,
        total: null,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20,
          importance: undefined,
          title: undefined,
          type: undefined,
          sort: '+id'
        },
        orderVO: {},
        product: {
          productId: undefined,
          productName: '',
          productNum: 1,
          productPrice: '',
          productTotalPrice: 0,
          productModel: '默认'
        },
        importanceOptions: [1, 2, 3],
        sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
        receiptTypeOption: [{
          value: '快递',
          label: '快递'
        }, {
          value: '自取',
          label: '自取'
        }],
        showReviewer: false,
        temp: {
          id: undefined,
          importance: 1,
          remark: '',
          timestamp: new Date(),
          title: '',
          type: ''
        },
        dialogProductVisible: false,
        dialogStatus: '',
        textMap: {
          update: '修改产品',
          create: '添加产品'
        },
        dialogPvVisible: false,
        pvData: [],
        rulesProduct: {
          type: [{ required: true, message: '必填', trigger: 'change' }],
          timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
          title: [{ }],
          price: [{ required: true, message: '单价不能为空' },
            { type: 'number', message: '单价必须为数字值' }],
          customer: [
            { required: true, message: '请选择活动区域', trigger: 'change' }
          ]
        },
        downloadLoading: false
      }
    },
    computed: {
    },
    watch: {
      createVisable(val, oldval) {
        if (val === true) {
          this.getOrder(this.orderId)
        }
      }
    },
    created() {
      this.getOrder(this.orderId)
      this.getAllProducts()
      this.getAllCustomers()
    },
    methods: {
      tableProductChange(row) {
        row.productTotalPrice = (row.productNum * row.productPrice)
        console.log(row.productNum * row.productPrice)
        console.log(row.productTotalPrice)
      },
      handleItemChange() {
        const vals = this.getCascaderObj(this.val, this.productOptions)
        this.product.productId = vals[1].value
        this.product.productName = vals[1].label
      },
      getCascaderObj(val, opt) {
        return val.map(function(value, index, array) {
          for (var itm of opt) {
            if (itm.value === value) {
              opt = itm.children
              return itm
            }
          }
          return null
        })
      },
      getAllCustomers() {
        findAllCustomerList().then(response => {
          this.customerOptions = response.data
        })
      },
      getAllProducts() {
        findAllProductList().then(response => {
          if (response.code !== 200) {
            this.$message({
              message: response.message,
              type: 'error'
            })
          } else {
            this.productData = response.data
            this.pushProductOptions(response.data)
          }
        })
      },
      pushProductOptions(products, selectProducts) {
        const newoption = []
        products.forEach(function(item, index, array) {
          let bl = -1
          newoption.forEach(function(item2, index2) {
            if (item.categoryId === item2.value) {
              bl = index2
              return
            }
          })

          let dis = false
          if (selectProducts !== null && selectProducts !== undefined) {
            var newArr = selectProducts.filter(function(val) {
              return val.productId === item.id
            })
            if (newArr.length > 0) {
              dis = true
            }
          }
          if (bl > -1) {
            newoption[bl].children.push({ 'value': item.id, 'disabled': dis, 'label': item.name })
          } else {
            newoption.push({
              'value': item.categoryId,
              'label': item.category,
              'children': [{ 'value': item.id, 'disabled': dis, 'label': item.name }]
            })
          }
        })
        this.productOptions = newoption
      },
      getOrder(orderId) {
        this.resetOrderVO()
        if (orderId != null && orderId !== undefined && orderId !== '') {
          this.productlistLoading = true
          findOrderById(orderId).then(response => {
            this.listLoading = false
            if (response.code !== 200) {
              this.$message({
                message: response.message,
                type: 'error'
              })
            } else {
              if (response.data != null) {
                this.orderVO = response.data
              }
              this.productlistLoading = false
            }
          })
        }
      },
      resetOrderVO() {
        this.orderVO = {
          id: '', // this.$route.params.id,
          customerId: '',
          customerName: '',
          receiptType: '快递',
          contacts: '',
          mobilePhone: '',
          address: '',
          logisticsName: '',
          logisticsNo: '',
          img: '',
          remark: '',
          status: '',
          orderProducts: []
        }
      },
      saveOrderHandle(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid && this.validateProducts()) {
            // 表单验证
            saveOrderList(this.orderVO).then(response => {
              this.resetForm('dataCreateOrderForm')
              this.orderVO.id = response.data
              this.getOrder(this.orderVO.id)
              this.$message({
                message: '下单成功',
                type: 'success'
              })
              this.$emit('refreshList')
            })
          } else {
            console.log('请检查数据是否完整!!')
            return false
          }
        })
      },
      updateOrderHandle(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid && this.validateProducts()) {
            // 表单验证
            updateOrderList(this.orderVO).then(response => {
              this.resetForm('dataCreateOrderForm')
              this.getOrder(this.orderVO.id)
              this.$message({
                message: '更新成功',
                type: 'success'
              })
              this.$emit('refreshList')
            })
          } else {
            console.log('请检查数据是否完整!!')
            return false
          }
        })
      },
      validateProducts() {
        if (this.orderVO.orderProducts === null || this.orderVO.orderProducts === undefined || this.orderVO.orderProducts.length <= 0) {
          this.$message({
            message: '请添加商品',
            type: 'error'
          })
          return false
        } else {
          return true
        }
      },
      deleteRow(index, rows) {
        rows.splice(index, 1)
      },
      resetForm(formName) {
        this.$refs[formName].resetFields()
      },
      resetProduct() {
        this.val = []
        this.product = {
          productId: '',
          productName: '',
          productNum: 1,
          productPrice: '',
          productTotalPrice: 0,
          productModel: '默认'
        }
      },
      unSelectDisable() {
        this.pushProductOptions(this.productData, this.orderVO.orderProducts)
      },
      handleAddProduct() {
        this.resetProduct()
        this.unSelectDisable()
        this.dialogStatus = 'create'
        this.dialogProductVisible = true
      },
      addDomain(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            const that = this
            if (this.orderVO.orderProducts === null || this.orderVO.orderProducts === undefined) {
              this.orderVO.orderProducts = []
            }
            if (that.product.productId === '' || that.product.productNum === '' || that.product.productPrice === '' || that.product.productModel === '') {
              this.$message({
                message: '请输入必填项!!',
                type: 'error'
              })
              return
            }
            this.orderVO.orderProducts.push({
              productId: that.product.productId,
              productName: that.product.productName,
              productNum: that.product.productNum,
              productPrice: that.product.productPrice,
              productTotalPrice: that.product.productNum * that.product.productPrice,
              productModel: that.product.productModel
            })
            this.dialogProductVisible = false
          } else {
            this.$message({
              message: '请检查后再提交!!',
              type: 'error'
            })
            return false
          }
        })
      }
    }
  }
</script>

<style scoped>

</style>
